<template>
	<div>
		<el-form :inline="true" ref="ruleFormRef" :model="ruleForm" class="demo-form-inline" label-width="auto">
			<el-form-item label="订单名称" prop="OrdersName">
				<el-input v-model="ruleForm.OrdersName" />
			</el-form-item>
			<el-form-item label="订单描述" prop="OrdersDesc">
				<el-input v-model="ruleForm.OrdersDesc" />
			</el-form-item>

			<el-form-item label="业务" prop="BusinessId">
				<el-select @change="Businesschange" v-model="ruleForm.BusinessId" style="width: 200px;" filterable
					placeholder="请选择你的业务">
					<el-option v-for="item in Business" :value="item.Id" :label="item.BusinessName"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="总金额" prop="SumPrice">
				<el-input disabled v-model="ruleForm.SumPrice" type="text" />
			</el-form-item>

			<el-form-item label="总经理" prop="MangerId">
				<el-select v-model="ruleForm.MangerId" style="width: 200px;" filterable placeholder="请选择总经理">
					<el-option v-for="item in Manger" :value="item.Id" :label="item.UserName"></el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="客户" prop="ClientId">
				<el-select v-model="ruleForm.ClientId" style="width: 200px;" filterable placeholder="请选择你的客户">
					<el-option v-for="item in Client" :value="item.Id" :label="item.ClientName"></el-option>
				</el-select>
				<ElButton type="primary" @click="addClient" style="margin-left: 10px;">添加客户</ElButton>
			</el-form-item>

			<br>

		</el-form>
		<hr>
		<div style="display: flex; align-items: center; justify-content: space-between;">
			<span style="font-weight: 600;">选择商品</span>
			<div>
				<ElButton @click="dele" size="large">移除</ElButton>
				<ElButton size="large" style="margin-left: 10px; " @click="selectproduct">选择商品</ElButton>
			</div>
		</div>
		<hr>
		<ElTable ref="addfilm" :data="orderitems" emptyText="暂无数据" height="40vh">
			<el-table-column type="selection" width="55" />
			<el-table-column fixed prop="Id" label="Id" width="50" />
			<el-table-column prop="ProductName" label="商品名称" width="120" />
			<el-table-column prop="ProductImg" label="预览图片" width="120">
				<template #default="scoped">
					<img :src="'http://localhost:5242/' + scoped.row.ProductImg" style="width: 100px;height: 80px;" />
				</template>
			</el-table-column>
			<el-table-column prop="Material" label="材质" width="140" />
			<el-table-column prop="Specifications" label="大小" width="150" />
			<el-table-column prop="Price" label="价格" width="150" />
			<ElTableColumn prop="Number" label="商品数量" width="100px">
				<template #default="scope">
					<el-input v-model="scope.row.Number" type="number" @change="numberChange(scope.row)" />
				</template>
			</ElTableColumn>
			<el-table-column prop="CreateTime" label="创建时间" width="180" />
			<el-table-column prop="Status" label="状态" width="60" />
		</ElTable>

		<hr>
		  <ElForm :inline="true" ref="Payinfoss" :model="Payinfo" class="demo-form-inline" label-width="auto">
			<div class="la">
				            <el-form-item label="付款方式">
					<div class="aa" >
						                <!-- <el-input v-model="Payinfo.PayName" type="text" /> -->
						<el-select v-model="Payinfo.PayName" style="width: 200px;" filterable placeholder="请选择你的付款方式" >
							<el-option v-for="item in Pay" :value="item.PayName" :label="item.PayName"></el-option>
						</el-select>
					</div>
					           
				</el-form-item>
				            <el-form-item label="付款人">
					<div class="el">
						                <el-input v-model="Payinfo.PayPerson" type="text" />
					</div>
					           
				</el-form-item>
				            <el-form-item label="付款描述">
					<div class="el">
						                <el-input v-model="Payinfo.PayManner" type="text" />
					</div>
					           
				</el-form-item>
				            <el-form-item label="付款金额">
					<div class="el">
						                <el-input v-model="Payinfo.Price" type="number" disabled />
					</div>
					           
				</el-form-item>
			</div>
			       
		</ElForm>
		        <el-drawer v-model="drawer" title="添加客户">
			            <clientadd v-if="drawer" @cloesdrawer="cloesdrawer"></clientadd>
			        </el-drawer>

		        <ElDialog title="商品" width="90%" v-model="SeleVisible" style="margin-top: 50px;">
			            <ProduList :seledata="orderitems" v-if="SeleVisible" @CloseSelect="CloseSelect"></ProduList>
			        </ElDialog>
		        <div style="width: 100%; height: 40px;">

			  <ElButton type="primary" style="position:absolute; bottom: 10px;right: 10px;margin-bottom: 95px;"
				@click="submitForm">保存
			</ElButton>
			 
			     </div>
	</div>
</template>

<script lang="ts" setup>
	import { ref, reactive, onMounted } from 'vue'
	import type { ComponentSize, FormInstance, FormRules, ElButton, ElTable, ElForm, ElDialog, ElInput } from 'element-plus';
	import { ElNotification, ElMessageBox, ElMessage } from 'element-plus';
	import ordersapi from '@/api/ordersapi';
	import clientapi from '@/api/clientapi';
	import userapi from '@/api/userapi';
	import businessapi from '@/api/Businessapi';
	import payapi from '@/api/payinfoapi';
	import clientadd from '../Client/ClientAdd.vue'
	import ProduList from '../Produ/ProduList.vue'

	const emit = defineEmits(['onSave'])

	//客户
	//const Client = ref([])
	const Client = ref<any[]>();
	//总经理
	//const Manger = ref([])
	const Manger = ref<any[]>();
	//业务员
	//const Business = ref([])
	const Business = ref<any[]>();
	//付款方式
	const Pay = ref<any[]>();
	//金额
	const BusinessPrice = ref(0)

	const drawer = ref(false)
	const orderitems = ref<any[]>([]);
	const SeleVisible = ref(false);
	const addfilm = ref<InstanceType<typeof ElTable>>()
	const Payinfo = ref(
		{
			PayName: "",
			PayManner: "",
			PayPerson: "",
			Price: 0
		}
	)
	interface RuleForm {
		OrdersName : string
		OrdersDesc : string
		BusinessId : number
		MangerId : number
		ClientId : number
		SumPrice : money
	}
	const ruleFormRef = ref<FormInstance>()
	const ruleForm = reactive<RuleForm>({
		OrdersName: '',
		OrdersDesc: '',
		BusinessId: "",
		MangerId: "",
		ClientId: "",
		SumPrice: "",
		Contract: '',
		Ordersitems: null as any | null,
		Payinfo: {
			PayName: "",
			PayManner: "",
			PayPerson: "",
			Price: 0
		}
	})


	//业务改变事件
	const Businesschange = () => {
		var dd : any = Business.value?.filter(o => o.Id == ruleForm.BusinessId)

		BusinessPrice.value = dd[0].Price
		ActionPrice();
	}
	//查询客户
	const getclient = () => {
		clientapi.select().then(res => {
			Client.value = res.data;
		}).catch(err => {
			console.log(err)
		})
	}
	//查询总经理
	const getmanger = () => {
		userapi.getall().then(res => {
			Manger.value = res.data;
		}).catch(err => {
			console.log(err)
		})
	}
	//查询业务员
	const getbuiness = () => {
		businessapi.select().then(res => {
			Business.value = res.data;
		}).catch(err => {
			console.log(err)
		})
	}
	//查询付款方式
	const getpay = () => {
		payapi.get().then(res => {
			Pay.value = res.data;
		}).catch(err => {
			console.log(err)
		})
	}

	//保存提交
	const submitForm = () => {
		var item : any[] = [];
		orderitems.value.forEach((val : any) => {
			item.push({
				GoodsName: val.ProductName,
				ProductImg: val.ProductImg,
				GoodsId: val.Id,
				Price: val.Price,
				Num: val.Number
			});
		});
		ruleForm.ordersitems = item
		ruleForm.Payinfo = Payinfo.value
		console.log("456=", ruleForm)
		ordersapi.Add(ruleForm).then(res => {
			console.log("res=", res.code)
			if (res.code > 0) {
				ElMessage.success("添加成功")
				emit("onSave", "Add")
			} else {
				ElMessage.error("添加失败")
			}
		}).catch(err => {
			console.log(err)
		})
	}

	//商品数量改变事件
	const numberChange = (val : any) => {
		if (val.Number == "") {
			val.Number = 1;
			ElMessage.error("数量不能为空")
			ActionPrice()
			return;
		}
		if (val.Number <= 0) {
			val.Number = 1;
			ElMessage.error("数量不能为小于0")
			ActionPrice()
			return;
		}
		ActionPrice()
	}
	//查询商品
	const CloseSelect = (data : any) => {
		orderitems.value = [];
		SeleVisible.value = false;
		data.forEach((val : any) => {
			let index = orderitems.value.indexOf(val);
			if (index == -1) {
				orderitems.value.push({
					Id: val.Id,
					ProductName: val.ProductName,
					Material: val.Material,
					Specifications: val.Specifications,
					Number: 1,
					Price: val.Price,
					CreateTime: val.CreateTime,
					Status: val.Status,
					ProductImg: val.ProductImg
				})
			}
		});
		ActionPrice();

	}

	//选择商品
	const selectproduct = () => {
		SeleVisible.value = true
	}
	//移除是商品
	const dele = () => {
		let ads = addfilm.value!.getSelectionRows()
		if (ads.length > 0) {
			ElMessageBox.confirm("请问是否删除这条数据吗", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}).then(() => {
				ads.forEach((val : any) => {
					let index = orderitems.value.indexOf(val);
					orderitems.value.splice(index, 1);
					orderitems.value.splice(index, 1);
				});
				ActionPrice()
			}).catch(() => { })
		} else {
			ElMessage({
				message: "请选择你要删除的数据",
				type: "error"
			})
		}

	}

	//计数价格
	const ActionPrice = () => {
		var num = 0;

		orderitems.value.forEach((val : any) => {
			num += val.Number * val.Price
		})

		ruleForm.SumPrice = BusinessPrice.value + num
		Payinfo.value.Price = BusinessPrice.value + num
	}
	const addClient = () => {
		drawer.value = true
	}
	async function cloesdrawer(val : any) {
		drawer.value = false;
		await getclient()
		ruleForm.value.ClientId = val;
	}
	onMounted(() => {
		getclient();
		getmanger();
		getbuiness();
		getpay();
	})
</script>


<style>
	.la {
		display: flex;
		float: left;

	}

	.el {
		margin-top: -40px;
		width: 185px;
	}
	.aa{
		margin-top: -40px;
		margin-left: -5px;
	}
</style>